package com.mango.amazon.convert;

import com.amazon.spapi.feeds_2021_06_30.model.CreateFeedDocumentResponse;
import com.amazon.spapi.feeds_2021_06_30.model.CreateFeedDocumentSpecification;
import com.amazon.spapi.feeds_2021_06_30.model.CreateFeedSpecification;
import com.amazon.spapi.feeds_2021_06_30.model.FeedOptions;
import com.mango.amazon.entity.FeedsEntity;
import com.mango.amazon.entity.Inventory;
import org.apache.poi.ss.formula.functions.T;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

public class FeedsConvert {


    public static CreateFeedDocumentSpecification toCreateFeedDocumentSpecification(FeedsEntity entity) {

        CreateFeedDocumentSpecification documentSpecification = new CreateFeedDocumentSpecification();
        // documentSpecification.setContentType("text/xml; charset=UTF-8");
        //documentSpecification.setContentType("application/json; charset=utf-8");
        documentSpecification.setContentType(String.format("text/xml; charset=%s", StandardCharsets.UTF_8));

        return documentSpecification;

    }


    public static CreateFeedSpecification toCreateFeedSpecification(FeedsEntity entity, CreateFeedDocumentResponse feedDocument) {
        if (entity == null) {
            return null;
        }
        CreateFeedSpecification createFeedSpecification = new CreateFeedSpecification();
        createFeedSpecification.setFeedType(entity.getFeedType().getTypeName());
        createFeedSpecification.setMarketplaceIds(entity.getMarketplaceIds());
        createFeedSpecification.setInputFeedDocumentId(feedDocument.getFeedDocumentId());
        createFeedSpecification.setFeedOptions((FeedOptions) entity.getFeedOptions());

        return createFeedSpecification;
    }


    public static String  entity2XML(Inventory inventory) {

        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(Inventory.class);

            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            // 将对象转换成输出流形式的xml
            // 创建输出流
            StringWriter stringWriter = new StringWriter();


            marshaller.marshal(inventory, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
}
